package com.lh.marketing.canvas.rules;

import com.lh.marketing.canvas.UserEnvVariable;
import com.lh.marketing.core.exception.CommonException;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;

/**
 * js解析器
 */
public class JavaScriptParser {

    /**
     * 执行js脚本
     * @param expression    表达式
     */
    public static boolean parseExpression(String expression, UserEnvVariable variable){
        Map<String, Object> emptyMap = Collections.emptyMap();
        String functionName = "parseExpression";
        String function = "function parseExpression($_user,$_event,$_system){return ${replaceVal}}";
        function = function.replace("${replaceVal}",expression);
        Object result = doSimpleScript(functionName,
                function,
                Optional.ofNullable(variable.getUserProperty()).orElse(emptyMap),
                Optional.ofNullable(variable.getUserEvent()).orElse(emptyMap),
                Optional.ofNullable(variable.getSystem()).orElse(emptyMap));
        if(result == null){
            return false;
        }
        return result.toString().toUpperCase().equals("TRUE");
    }

    /**
     * 执行脚本
     * @param function  脚本方法
     * @param params    方法参数
     * @return  执行结果
     */
    private static Object doSimpleScript(String functionName,String function,Object...params){
        try {
            ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
            engine.eval(function);
            // 可有调用方法
            Invocable invoke = (Invocable) engine;
            // 调用方法，此处无参数列表
            return invoke.invokeFunction(functionName, params);
        }catch (Exception e) {
            throw new CommonException(e);
        }
    }
}
